package com.longjianghuasheng.logistics.ext

import android.app.Activity
import android.app.Dialog
import android.content.DialogInterface
import android.content.Intent
import android.content.res.ColorStateList
import android.graphics.Paint
import android.net.Uri
import android.text.InputType
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.style.AbsoluteSizeSpan
import android.text.style.ForegroundColorSpan
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.webkit.WebView
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.widget.Toolbar
import androidx.fragment.app.Fragment
import androidx.navigation.NavOptions
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import coil.load
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.SizeUtils
import com.blankj.utilcode.util.TimeUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.longjianghuasheng.logistics.R
import com.longjianghuasheng.logistics.business.advisory.AskForAQuotationFragment
import com.longjianghuasheng.logistics.business.freight.FreightFragment
import com.longjianghuasheng.logistics.business.grab_an_order.GrabAnOrderListFragment
import com.longjianghuasheng.logistics.business.home.HomeFragment
import com.longjianghuasheng.logistics.business.mine.fragment.DriverMineFragment
import com.longjianghuasheng.logistics.business.mine.fragment.MineFragment
import com.longjianghuasheng.logistics.network.NetworkApi
import com.longjianghuasheng.logistics.network.stateCallback.ListDataUiState
import com.longjianghuasheng.logistics.util.CacheUtil
import com.longjianghuasheng.logistics.util.SettingUtil
import com.longjianghuasheng.logistics.weight.GlideEngine
import com.longjianghuasheng.logistics.weight.recyclerview.DefineLoadMoreView
import com.longjianghuasheng.logistics.weight.recyclerview.GridListItemDecoration
import com.longjianghuasheng.logistics.weight.recyclerview.SpaceItemDecoration
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.listener.OnResultCallbackListener
import com.xuexiang.xui.XUI
import com.xuexiang.xui.utils.DensityUtils
import com.xuexiang.xui.utils.WidgetUtils
import com.xuexiang.xui.widget.dialog.materialdialog.DialogAction
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog
import com.xuexiang.xui.widget.picker.widget.builder.OptionsPickerBuilder
import com.xuexiang.xui.widget.picker.widget.builder.TimePickerBuilder
import com.xuexiang.xui.widget.popupwindow.popup.XUIPopup
import com.xuexiang.xui.widget.statelayout.StatefulLayout
import com.xuexiang.xui.widget.textview.supertextview.SuperTextView
import com.yanzhenjie.recyclerview.SwipeRecyclerView
import me.hgj.jetpackmvvm.base.appContext
import java.math.BigDecimal
import java.text.NumberFormat
import java.util.regex.Pattern
import kotlin.math.abs


/**
 * 作者　: hegaojian
 * 时间　: 2020/2/20
 * 描述　:项目中自定义类的拓展函数
 */


fun ImageView.loadUrl(url: String?) {
    load(url) {
        placeholder(R.drawable.shape_album_loading_bg)
        error(R.drawable.shape_album_loading_bg)
        crossfade(true) //淡入淡出
    }
}

fun RecyclerView.initDivide(
    bindAdapter: BaseQuickAdapter<*, *>,
) {

    setHasFixedSize(true)
    isNestedScrollingEnabled = false
    WidgetUtils.initRecyclerView(this, 1, ColorUtils.getColor(R.color.baseBackground))
    adapter = bindAdapter
    bindAdapter.setAdapterAnimation()
}


//绑定普通的Recyclerview
fun RecyclerView.init(
    layoutManger: RecyclerView.LayoutManager,
    bindAdapter: BaseQuickAdapter<*, *>,
    isScroll: Boolean = true,
    isAnimation: Boolean = true

): RecyclerView {
    layoutManager = layoutManger
    setHasFixedSize(true)
    adapter = bindAdapter
    bindAdapter.setAdapterAnimation(if (isAnimation) 1 else 0)
    isNestedScrollingEnabled = isScroll
    return this
}

fun RecyclerView.initGridDecoration(
    spanCount: Int = 2,
    space: Float = 10F,
    headFootSpace: Float = 20F,
    adapter: BaseQuickAdapter<*, *>
): RecyclerView {

    if (itemDecorationCount != 0) {

        return this
    }
    addItemDecoration(GridListItemDecoration(spanCount, space, headFootSpace))

    return init(GridLayoutManager(context, spanCount), adapter, false)
}

fun RecyclerView.initLinerDecoration(
    leftRight: Int = 0,
    space: Float = 10F,
    adapter: BaseQuickAdapter<*, *>
): RecyclerView {

    if (itemDecorationCount != 0) {

        return this
    }

    addItemDecoration(
        SpaceItemDecoration(
            leftRight,
            SizeUtils.dp2px(space),
        )
    )

    return init(LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false), adapter, false)
}


//初始化 SwipeRefreshLayout
fun SwipeRefreshLayout.init(onRefreshListener: () -> Unit) {
    this.run {
        setOnRefreshListener {
            onRefreshListener.invoke()
        }
        //设置主题颜色
        setColorSchemeColors(SettingUtil.getColor(appContext))
    }
}

fun SwipeRecyclerView.initFooter(loadmoreListener: SwipeRecyclerView.LoadMoreListener): DefineLoadMoreView {
    val footerView = DefineLoadMoreView(appContext)
    //给尾部设置颜色
    footerView.setLoadViewColor(SettingUtil.getOneColorStateList(appContext))
    //设置尾部点击回调
    footerView.setmLoadMoreListener {
        footerView.onLoading()
        loadmoreListener.onLoadMore()
    }
    this.run {
        //添加加载更多尾部
        addFooterView(footerView)
        setLoadMoreView(footerView)
        //设置加载更多回调
        setLoadMoreListener(loadmoreListener)
    }
    return footerView
}


/**
 * 初始化普通的toolbar 只设置标题
 */
fun Toolbar.init(titleStr: String = ""): Toolbar {
    setBackgroundColor(SettingUtil.getColor(appContext))
    title = titleStr
    return this
}

/**
 * 初始化有返回键的toolbar
 */
fun Toolbar.initClose(
    titleStr: String = "",
    backImg: Int = R.drawable.ic_back,
    onBack: (toolbar: Toolbar) -> Unit
): Toolbar {
    setBackgroundColor(SettingUtil.getColor(appContext))
    title = titleStr.toHtml()
    setNavigationIcon(backImg)
    setNavigationOnClickListener { onBack.invoke(this) }
    return this
}


//设置适配器的列表动画
fun BaseQuickAdapter<*, *>.setAdapterAnimation(mode: Int = 1) {
    //等于0，关闭列表动画 否则开启
    if (mode == 0) {
        this.animationEnable = false
    } else {
        this.animationEnable = true
        isAnimationFirstOnly = true
        this.setAnimationWithDefault(BaseQuickAdapter.AnimationType.values()[mode - 1])
    }
}


fun ViewPager2.init(
    fragment: Fragment,
    fragments: ArrayList<Fragment>,
    isUserInputEnabled: Boolean = true
): ViewPager2 {
    //是否可滑动
    this.isUserInputEnabled = isUserInputEnabled
    //设置适配器
    adapter = object : FragmentStateAdapter(fragment) {
        override fun createFragment(position: Int) = fragments[position]
        override fun getItemCount() = fragments.size
    }
    return this
}


fun ViewPager2.initMain(fragment: Fragment): ViewPager2 {
    //是否可滑动
    this.isUserInputEnabled = false
    this.offscreenPageLimit = 4
    //设置适配器
    adapter = object : FragmentStateAdapter(fragment) {
        override fun createFragment(position: Int): Fragment = when (position) {
            0 -> if (CacheUtil.isDriver) FreightFragment() else HomeFragment()
            1 -> if (CacheUtil.isDriver) GrabAnOrderListFragment() else FreightFragment()
            2 -> AskForAQuotationFragment()
            3 -> if (CacheUtil.isDriver) DriverMineFragment() else MineFragment()
            else -> HomeFragment()
        }

        override fun getItemCount() = 5
    }
    return this
}


fun BottomNavigationView.init(navigationItemSelectedAction: (Int) -> Unit): BottomNavigationView {
    itemIconTintList = SettingUtil.getColorStateList(SettingUtil.getColor(appContext))
    itemTextColor = SettingUtil.getColorStateList(appContext)
    setOnNavigationItemSelectedListener {


//        if ((it.itemId == R.id.menu_mine || it.itemId == R.id.menu_shop_car) && !CacheUtil.isLogin()) {
//            nav(this).navigateAction(R.id.loginFragment, navOptions = navOptions())
//            return@setOnNavigationItemSelectedListener false
//        }

        navigationItemSelectedAction.invoke(it.itemId)
        true
    }
    return this
}


/**
 * 拦截BottomNavigation长按事件 防止长按时出现Toast ---- 追求完美的大屌群友提的bug
 * @receiver BottomNavigationView
 * @param ids IntArray
 */
fun BottomNavigationView.interceptLongClick(vararg ids: Int) {
    val bottomNavigationMenuView: ViewGroup = (this.getChildAt(0) as ViewGroup)
    for (index in ids.indices) {
        bottomNavigationMenuView.getChildAt(index).findViewById<View>(ids[index])
            .setOnLongClickListener {
                true
            }
    }
}

/**
 * 隐藏软键盘
 */
fun hideSoftKeyboard(activity: Activity?) {
    activity?.let { act ->
        val view = act.currentFocus
        view?.let {
            val inputMethodManager =
                act.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
            inputMethodManager.hideSoftInputFromWindow(
                view.windowToken,
                InputMethodManager.HIDE_NOT_ALWAYS
            )
        }
    }
}

/**
 * 加载列表数据
 */
fun <T> loadListData(
    data: ListDataUiState<T>,
    baseQuickAdapter: BaseQuickAdapter<T, *>,
    loadService: StatefulLayout,
    recyclerView: SwipeRecyclerView,
    swipeRefreshLayout: SwipeRefreshLayout,
    block: (ArrayList<T>) -> Unit,
    errorClick: (View) -> Unit = {}
) {
    swipeRefreshLayout.isRefreshing = false
    recyclerView.loadMoreFinish(data.isEmpty, data.hasMore)
    if (data.isSuccess) {
        //成功
        when {
            //第一页并没有数据 显示空布局界面
            data.isFirstEmpty -> {
                loadService.showEmpty()
            }
            //是第一页
            data.isRefresh -> {
                block.invoke(data.listData)
//                baseQuickAdapter.setList(data.listData)
                loadService.showContent()


            }
            //不是第一页
            else -> {
                baseQuickAdapter.addData(data.listData)
                loadService.showContent()
            }
        }
    } else {
        //失败
        if (data.isRefresh) {
            //如果是第一页，则显示错误界面，并提示错误信息
            loadService.showError(data.errMessage, errorClick)
        } else {
            recyclerView.loadMoreError(0, data.errMessage)
        }
    }
}

//百分比
fun getPercentage(molecular: Float, denominator: Float, fractionDigits: Int = 1): Float {

    val numberFormat = NumberFormat.getInstance()
    numberFormat.maximumFractionDigits = fractionDigits
    val format =
        numberFormat.format((molecular / denominator)) //所占百分比

    return abs(format.toFloat())
}


//折叠布局滚动监听 ，回调alpha值
inline fun AppBarLayout.addOnOffsetChangedListener(crossinline block: (Float) -> Unit) {
    addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { appBarLayout, verticalOffset ->

        block(getPercentage(verticalOffset.toFloat(), appBarLayout.totalScrollRange.toFloat()))

    })

}

//选择器
fun Fragment.showPicker(title: String? = "", options: Array<String>, block: (String) -> Unit) {

    var selectOption = 0
    val pvOptions = OptionsPickerBuilder(context) { _, options1, _, _ ->
        selectOption = options1
        block(options[options1])
        false
    }.setTitleText(title)
        .setSelectOptions(selectOption)
        .setCancelText(requireContext().getString(R.string.cancel))
        .setSubmitText(requireContext().getString(R.string.dialog_confirm))
        .build<String>()
    pvOptions.setPicker(options)
    pvOptions.show()

}

//输入对话框
fun Fragment.showEdtDialog(
    content: String,
    hint: String,
    prefill: String = "",
    isNumber: Boolean = true,
    block: (String) -> Unit
) {

        MaterialDialog.Builder(requireContext())
            .content(content)
            .inputType(
                if (isNumber) InputType.TYPE_CLASS_NUMBER else InputType.TYPE_CLASS_TEXT
            )
            .input(
                hint,
                prefill,
                false,
                ({ dialog, input ->
                    block.invoke(input.toString())
                })
            )
//        .inputRange(3, 5)
            .positiveText(R.string.dialog_confirm)
            .negativeText(R.string.cancel)
            .onPositive { dialog: MaterialDialog, which: DialogAction? ->


//            block.invoke(dialog.inputEditText?.text.toString())
            }
            .cancelable(false)
            .show()


}

fun getUserTextStyle(content: String): SpannableStringBuilder {
    val z = content.indexOf(":") + 1
    val style = SpannableStringBuilder(content)
    style.setSpan(
        AbsoluteSizeSpan(SizeUtils.sp2px(15F)),
        0,
        1,
        Spannable.SPAN_EXCLUSIVE_INCLUSIVE
    ) //字号

    style.setSpan(
        ForegroundColorSpan(ColorUtils.getColor(R.color.gray9a)),
        z,
        content.length,
        Spannable.SPAN_EXCLUSIVE_INCLUSIVE
    ) //颜色

    style.setSpan(
        AbsoluteSizeSpan(SizeUtils.sp2px(15F)),
        z,
        content.length,
        Spannable.SPAN_EXCLUSIVE_INCLUSIVE
    ) //字号

    return style
}

fun TextView.setUserText(content: String) {
    text = getUserTextStyle(content)
}

fun SuperTextView.setUserText(content: String) {

    leftTextView.text = getUserTextStyle(content)


}


//中划线
fun TextView.underline() {

    paint.flags = Paint.STRIKE_THRU_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG

}


//保留两位小数
fun Double.getString(): String =
    BigDecimal(this).setScale(2, BigDecimal.ROUND_HALF_UP).toString()

//统一管理fragment过渡动画
fun navOptions(block: NavOptions.Builder.() -> NavOptions.Builder = { this }) =
    NavOptions.Builder()
//                        app:enterAnim="@anim/slide_in_right"
        .setEnterAnim(R.anim.slide_in_right)
//                        app:exitAnim="@anim/slide_out_left"
        .setExitAnim(R.anim.slide_out_left)
//                        app:popEnterAnim="@anim/slide_in_left"
        .setPopEnterAnim(R.anim.slide_in_left)
//                        app:popExitAnim="@anim/slide_out_right"
        .setPopExitAnim(R.anim.slide_out_right).block().build()


//单张图片选择
fun Fragment.selectPicture(block: (LocalMedia) -> Unit) {

    PictureSelector.create(this)
        .openGallery(PictureMimeType.ofImage())
        .isSingleDirectReturn(true)
        .selectionMode(PictureConfig.SINGLE)
        .imageEngine(GlideEngine.createGlideEngine()) // Please refer to the Demo GlideEngine.java
        .forResult(object : OnResultCallbackListener<LocalMedia> {
            override fun onResult(result: MutableList<LocalMedia>?) {
                if (result.isNullOrEmpty()) return

                block.invoke(result[0])

            }

            override fun onCancel() {

            }
        })

}

//拍照
fun Fragment.photograph(block: (LocalMedia) -> Unit) {
    PictureSelector.create(this)
        .openCamera(PictureMimeType.ofImage())
        .loadImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
        .forResult(object : OnResultCallbackListener<LocalMedia> {
            override fun onResult(result: MutableList<LocalMedia>?) {
                if (result.isNullOrEmpty()) return

                block.invoke(result[0])

            }

            override fun onCancel() {

            }
        })

}

//多张图片选择
fun Fragment.selectPictureMore(
    mSelectList: List<LocalMedia>,
    block: (List<LocalMedia>) -> Unit
) {
    PictureSelector.create(this)
        .openGallery(PictureMimeType.ofImage())
        .maxSelectNum(5)
        .minSelectNum(1)
        .selectionMode(PictureConfig.MULTIPLE)
        .isCamera(true)
        .imageEngine(GlideEngine.createGlideEngine()) // Please refer to the Demo GlideEngine.java
        .selectionData(mSelectList)
        .forResult(object : OnResultCallbackListener<LocalMedia> {
            override fun onResult(result: MutableList<LocalMedia>?) {
                if (result.isNullOrEmpty()) return

                block.invoke(result)

            }

            override fun onCancel() {

            }
        })
}


fun toEvaluatePercentage(score: String?) = NumberFormat.getInstance().run {

    // 设置精确到小数点后2位,可以写0不带小数位
    maximumFractionDigits = 0

    format((score?.toFloat() ?: 0F) / 5.0F * 100).toInt()

}


// 过滤html标签
fun String.htmlToString(): String {
    val REGEX_HTML = "<[^>]+>";

    val matcher =
        Pattern.compile("<br/>", Pattern.CASE_INSENSITIVE).matcher(this).replaceAll("\n\n")

    return Pattern.compile(REGEX_HTML, Pattern.CASE_INSENSITIVE).matcher(matcher).replaceAll("")

}

fun View.showPop(content: String) {

    val mNormalPopup = XUIPopup(context)
    val textView = TextView(context)
    textView.layoutParams = mNormalPopup.generateLayoutParam(
        DensityUtils.dp2px(context, 250f),
        ViewGroup.LayoutParams.WRAP_CONTENT
    )
    textView.setLineSpacing(DensityUtils.dp2px(4f).toFloat(), 1.0f)
    val padding = DensityUtils.dp2px(20f)
    textView.setPadding(padding, padding, padding, padding)
    textView.text = content
//    textView.setTextColor(
//        ContextCompat.getColor(
//            context,
//            R.color.xui_config_color_content_text
//        )
//    )
    textView.typeface = XUI.getDefaultTypeface()
    mNormalPopup.setContentView(textView)
    mNormalPopup.setAnimStyle(XUIPopup.ANIM_GROW_FROM_CENTER)
    mNormalPopup.setPreferredDirection(XUIPopup.DIRECTION_TOP)
    mNormalPopup.show(this)
}


fun Button.changeBtn(block: () -> Boolean) {
    isClickable = block.invoke()
    backgroundTintList =
        ColorStateList.valueOf(ColorUtils.getColor(if (block.invoke()) R.color.btnColor else R.color.grayDe))
}

fun Fragment.showAppointmentSuccessfulDialog(block: (DialogInterface) -> Unit) {
    val inflater = LayoutInflater.from(requireContext())
    val mDialog = Dialog(requireContext(), R.style.Mdialog)
    mDialog.setOnDismissListener(block)
    val mView: View = inflater.inflate(R.layout.dialog_appointment_successful, null).apply {
        findViewById<ImageView>(R.id.iv_close).setOnClickListener {

            mDialog.dismiss()
        }
    }
    mDialog.setContentView(mView)
    mDialog.window?.run {
        setGravity(Gravity.CENTER)
        setWindowAnimations(R.style.ScaleAnimStyle)
    }
    mDialog.setCanceledOnTouchOutside(true)
    mDialog.show()

}

fun String.judge(str: String): Boolean {

    if (isBlank()) {
        toastNormal(str)
        return true
    }
    return false
}

//时间选择器
fun Fragment.showTimePicker(block: (String) -> Unit) {

    TimePickerBuilder(context) { date, _ ->

        block.invoke(TimeUtils.date2String(date, "yyyy-MM-dd"))

    }.build().show()
}


fun WebView.loadRichText(richText: String, isJointUrl: Boolean = false) {
    val newTextStart = """
                
        <html>
             
             <head>
             
             <meta name='viewport' content='width=device-width,initial-scale=1.0, maximum-scale=1.0, user-scalable=0'>
                
                
             </head>
           <body>
                
        
    """.trimIndent()
    val newsTextEnd = """
            <style type="text/css"> img {
         
                width:100% !important;
                height:auto !important;
         
                 }
            </style>
           </body>
       </html>
        
    """.trimIndent()
    val replace =
        richText.replace(
            "<img src=\"",
            "<img src=\"${NetworkApi.BASE_URL}"
        )
    loadData(
        "$newTextStart ${if (isJointUrl) replace else richText} $newsTextEnd",
        "text/html",
        "utf-8"
    )
}

fun Fragment.openPhone(phone: String) {
    startActivity(Intent(Intent.ACTION_DIAL, Uri.parse("tel:$phone")))
}

fun Fragment.showQrCodeDialog(qrCodeUrl: String) {
    val inflater = LayoutInflater.from(requireContext())
    val mDialog = Dialog(requireContext(), R.style.Mdialog)
    val mView: View = inflater.inflate(R.layout.dialog_qr_code, null).apply {
        findViewById<ImageView>(R.id.iv_qr_code).loadUrl(qrCodeUrl)

    }
    mDialog.setContentView(mView)
    mDialog.window?.run {
        setGravity(Gravity.CENTER)
        setWindowAnimations(R.style.ScaleAnimStyle)
    }
    mDialog.setCanceledOnTouchOutside(true)
    mDialog.show()

}
